import axios from "axios";
import { Message } from "element-ui";
import router from "../main";
import { SUCCESS_CODE, TOKEN_FAILURE, NO_POWER } from "@/config";
// http request 拦截器
axios.interceptors.request.use(
    config => {
        config.headers = {
            // contentTypeJson Content-Type为json格式
            "Content-Type": !config.contentTypeJson
                ? "application/x-www-form-urlencoded"
                : "application/json",
            token: window.sessionStorage.token || ""
        };
        config.withCredentials = true;
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);
// http response 拦截器
axios.interceptors.response.use(
    response => {
        if (response.data.code !== SUCCESS_CODE) {
            if (response.data.code == NO_POWER) {
                Message.error(response.data.message);
            } else if (response.data.code == TOKEN_FAILURE) {
                Message.error("登录失效");
                router.replace({
                    path: "login"
                });
            } else {
                Message.error({
                    message: response.data.message,
                    customClass: "global-toast"
                });
            }
            return Promise.reject(response);
        }
        return response.data;
        // return response;
    },
    error => {
        console.log(error, "error");
        Message.error({
            message: error.data.message || "网络挂啦，请求不到数据！",
            customClass: "global-toast"
        });
        return Promise.reject(error.data);
    }
);
export default axios;
